package com.ecplatform.api.config;

import com.ecplatform.common.utils.UserContext;
import feign.Client;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.okhttp.OkHttpClient;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient.Builder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class FeignConfig {

    @Bean
    public Client feignClient() {
        return new OkHttpClient(new Builder().build());
    }

    @Bean
    public RequestInterceptor userInfoRequestInterceptor() {
        log.error("----------------FeignConfig 的 userInfoInterceptor--------------");
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 获取登录用户
                Long userId = UserContext.getUserId();
                if (userId != null) {
                    // 如果为空直接跳过
                    return;
                }

                // 如果不为空则放入请球头中，传递给下游服务
                requestTemplate.header("user-info", userId.toString());
            }
        };
    }
}
